using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AppDown.Controllers.Base;
using AppDown.Db.Models;
using System.ComponentModel.DataAnnotations;

namespace AppDown.Controllers;
/// <summary>
/// APP下载
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class AppDownController : BaseApi
{
    /// <summary>
    /// 获取环境信息
    /// </summary>
    public readonly IWebHostEnvironment _webHostEnvironment;

    /// <summary>
    /// AppDownController 类用于处理应用程序下线相关的操作。
    /// </summary>
    /// <param name="webHostEnvironment">IWebHostEnvironment 接口实例，提供有关当前WebHost的信息。</param>
    public AppDownController(IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment = webHostEnvironment;
    }

    /// <summary>
    /// 默认系统初始化，无权限，只能初始化一次
    /// </summary>
    /// <returns></returns>
    [HttpGet("init")]
    public ApiResult DefaultInitSystem()
    {
        if (CheckIsInitSystem())
        {
            return Success(1, "系统已初始化成功，请勿重复操作");
        }

        //不存在创建数据库存在不会重复创建
        db.DbMaintenance.CreateDatabase();

        //清空表
        if (db.DbMaintenance.IsAnyTable(nameof(AppDownLoad), false)) db.DbMaintenance.DropTable(nameof(AppDownLoad));

        //初始化表
        db.CodeFirst.InitTables<AppDownLoad>();

        return SuccessMsg("初始化完成");
    }

    /// <summary>
    /// 上传APP
    /// </summary>
    /// <returns></returns>
    [HttpPost("upload")]
    public async Task<ApiResult> Upload([FromForm] UploadAppDto dto)
    {
        string fileExtension = Path.GetExtension(dto.FormFile.FileName);
        if (!fileExtension.Equals(".apk", StringComparison.OrdinalIgnoreCase))
        {
            return Error("文件格式不正确, 需要为apk格式");
        }
        string fileNameExtension = Path.GetExtension(dto.FileName);
        if (!fileNameExtension.Equals(".apk", StringComparison.OrdinalIgnoreCase))
        {
            return Error("文件名FileName格式不正确, 需要为apk格式");
        }

        var fileRelativePath = Path.Combine("app", dto.AppVersion);
        var fileRelativePathIncludeFileName = Path.Combine(fileRelativePath, dto.FileName);
        var fileAbsolutePath = Path.Combine(_webHostEnvironment.WebRootPath, fileRelativePath);
        var fileAbsolutePathIncludeFileName = Path.Combine(fileAbsolutePath, dto.FileName);
        if (dto.FormFile.Length > 0)
        {
            // 路径确保存在
            if (!Directory.Exists(fileAbsolutePath)) Directory.CreateDirectory(fileAbsolutePath);
            // 写入文件
            using (var stream = System.IO.File.Create(fileAbsolutePathIncludeFileName))
            {
                await dto.FormFile.CopyToAsync(stream);
            }
        }

        // 使用Replace方法替换双（反）斜杠
        // var androidUrl = GetHost() + "/api/AppDown/" + fileRelativePathIncludeFileName.Replace("\\", "/").Replace("//", "/");

        var androidUrl = Path.Combine(GetHost(), fileRelativePathIncludeFileName);
        // 保存文件连接地址
        var appDownLoad = new AppDownLoad()
        {
            FileName = dto.FileName,
            AppVersion = dto.AppVersion,

            AndroidUrl = androidUrl,
            IosUrl = dto.IosUrl
        };

        await db.Insertable<AppDownLoad>(appDownLoad).ExecuteCommandAsync();

        return Success(appDownLoad, "上传完成");
    }

    /// <summary>
    /// 获取最新APP下载链接
    /// </summary>
    /// <returns></returns>
    [HttpGet("getVersion")]
    public async Task<ApiResult> GetVersion()
    {
        var info = await db.Queryable<AppDownLoad>()
                    .OrderByDescending(a => a.AppVersion)
                    .OrderByDescending(a => a.CreateTime)
                    .Where(a => a.Status == 0)
                    .FirstAsync();
        return Success(info);
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <param name="fileName">文件名（包含后缀）</param>
    /// <returns></returns>
    [HttpGet("app/{path}/{fileName}")]
    public IActionResult Download(string path, string fileName)
    {
        string filePath = Path.Combine(AppContext.BaseDirectory, "app", path, fileName);
        if (!System.IO.File.Exists(filePath))
        {
            return NotFound();
        }

        var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
        return File(fileStream, "application/octet-stream", fileName);
    }

    /// <summary>
    /// 获取当前HTTP请求的完整主机地址（包括协议 scheme 和主机名）。
    /// </summary>
    /// <returns>当前请求的完整主机地址，格式为 "scheme://host"。</returns>
    private string GetHost()
    {
        // 获取当前请求的Scheme（例如HTTP或HTTPS）
        string scheme = HttpContext.Request.Scheme;
        // 获取当前请求的主机名（包括端口号，如果有的话）
        var host = HttpContext.Request.Host.ToString();
        // 将Scheme和主机名连接起来形成完整的主机地址
        return scheme + "://" + host;
    }

    /// <summary>
    /// 上传APP的DTO
    /// </summary>
    public class UploadAppDto
    {
        /// <summary>
        /// apk程序文件
        /// </summary>
        [Required]
        public IFormFile FormFile { get; set; }
        /// <summary>
        /// apk程序文件文件名(包含后缀)
        /// </summary>
        [Required]
        public string FileName { get; set; }
        /// <summary>
        /// IOS商店地址，例如 https://apps.apple.com/cn/app/%E9%92%89%E9%92%89/id930368978
        /// </summary>
        [Required]
        public string IosUrl { get; set; }
        /// <summary>
        /// App版本号
        /// </summary>
        [Required]
        public string AppVersion { get; set; }
    }
}
